<template>
  <div class="users-container">

    <div class="main-card">
      <!-- 页面标题 -->
      <div class="card-header">
        <h2 class="card-title">用户管理</h2>
      </div>
      <div class="search-section">
        <div class="search-container">
          <div class="search-item">
            <span class="search-label">用户名称</span>
            <el-input v-model="queryParams.name" placeholder="请输入用户名称" clearable @keyup.enter="handleQuery"
              class="search-input">
              <template #prefix>
                <el-icon>
                  <User />
                </el-icon>
              </template>
            </el-input>
          </div>
          <div class="search-item">
            <span class="search-label">用户状态</span>
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @clear="handleClear"
              class="search-select">
              <el-option label="正常" :value="0" />
              <el-option label="封禁" :value="1" />
            </el-select>
          </div>
          <div class="search-buttons">
            <el-button type="primary" @click="handleQuery" :icon="Search">查询</el-button>
            <el-button @click="resetQuery" :icon="RefreshRight">重置</el-button>
          </div>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table :data="userList" fit v-loading="loading" border stripe highlight-current-row
          :cell-style="{ textAlign: 'center' }">
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="name" label="用户名称" align="center" />
          <el-table-column label="头像" align="center">
            <template #default="{ row }">
              <el-avatar :size="40" :src="row.avatar" class="user-avatar">
                <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
              </el-avatar>
            </template>
          </el-table-column>

          <el-table-column label="IP位置" align="center">
            <template #default="{ row }">
              <div v-if="row.ipInfo" class="ip-info">
                <el-icon>
                  <Location />
                </el-icon>
                <span>{{ formatIpLocation(row.ipInfo) }}</span>
              </div>
              <el-tag v-else type="info" effect="plain">未知位置</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column prop="updateTime" label="更新时间" align="center" />
          <el-table-column label="角色" width="120" align="center">
            <template #default="{ row }">
              <div class="role-tags">
                <template v-if="row.roles && row.roles.length">
                  <el-tag v-for="role in row.roles" :key="role" :type="roleConfig[role]?.type || 'warning'"
                    :effect="roleConfig[role]?.effect || 'plain'" class="role-tag">
                    {{ roleConfig[role]?.label || role }}
                  </el-tag>
                </template>
                <el-tag v-else type="warning" effect="plain">未知</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center">
            <template #default="{ row }">
              <el-switch v-model="row.status" :active-value="0" :inactive-value="1" active-color="#13ce66"
                inactive-color="#ff4949" @change="throttledStatusChange(row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleView(row)" class="action-button">
                <el-icon>
                  <View />
                </el-icon>
                <span>查看</span>
              </el-button>
              <el-button type="success" link @click="handleEdit(row)" class="action-button">
                <el-icon>
                  <Edit />
                </el-icon>
                <span>编辑</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]" background layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="dialogVisible" title="用户详情" destroy-on-close>
      <div v-if="currentUser" class="user-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名称">{{ currentUser.name }}</el-descriptions-item>
          <el-descriptions-item label="IP位置">{{ formatIpLocation(currentUser.ipInfo) }}</el-descriptions-item>
          <el-descriptions-item label="角色">
            <div>
              <template v-if="currentUser.roles && currentUser.roles.length">
                <el-tag v-for="role in currentUser.roles" :key="role" :type="roleConfig[role]?.type || 'warning'"
                  :effect="roleConfig[role]?.effect || 'plain'">
                  {{ roleConfig[role]?.label || role }}
                </el-tag>
              </template>
              <el-tag v-else type="warning" effect="plain">未知</el-tag>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentUser.status === 0 ? 'success' : 'danger'">
              {{ currentUser.status === 0 ? '正常' : '封禁' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentUser.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentUser.updateTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 用户编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户" width="500px" destroy-on-close>
      <el-form v-if="editForm" :model="editForm" label-width="100px" :rules="rules" ref="editFormRef">
        <el-form-item label="用户头像" prop="avatar">
          <div class="avatar-uploader">
            <el-avatar v-if="editForm.avatar" :size="80" :src="editForm.avatar" class="avatar-preview">
            </el-avatar>
            <el-upload 
              class="avatar-upload" 
              action="#" 
              :auto-upload="false" 
              :show-file-list="false"
              :on-change="handleAvatarChange"
              accept="image/jpeg,image/png,image/gif,image/jpg"
            >
              <el-button type="primary">更换头像</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">封禁</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户角色" prop="roles">
          <el-select v-model="editForm.roles" multiple placeholder="请选择用户角色" style="width: 100%">
            <el-option v-for="role in roleList" :key="role.name" :label="role.description" :value="role.name" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit" :loading="submitLoading">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { getPageList, getById, save, updateStatus } from '@/api/user'
import { uploadFile } from '@/api/file'
import { getRolePageList } from '@/api/role'
import { debounce, throttle } from 'lodash-es'
import { User, Search, RefreshRight, Location, View, Edit } from '@element-plus/icons-vue'

// 查询参数
const queryParams = reactive({
  name: '',
  status: undefined,
  pageNum: 1,
  pageSize: 10
})


// 数据列表
const userList = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const currentUser = ref(null)

// 编辑相关
const editDialogVisible = ref(false)
const editForm = ref(null)
const editFormRef = ref(null)
const submitLoading = ref(false)
const avatarFile = ref(null)
const roleList = ref([]) // 角色列表数据

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入用户名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择用户状态', trigger: 'change' }
  ],
  roles: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ]
}

// 角色配置映射
const roleConfig = {
  admin: {
    label: '管理员',
    type: 'danger',
    effect: 'dark'
  },
  common: {
    label: '普通用户',
    type: 'success',
    effect: 'light'
  },
  // 可以在这里添加更多角色配置
  // 例如：
  // editor: {
  //   label: '编辑',
  //   type: 'primary',
  //   effect: 'light'
  // },
  // viewer: {
  //   label: '查看者',
  //   type: 'info',
  //   effect: 'light'
  // }
}

// 防抖处理查询
const debouncedQuery = debounce(() => {
  getUserList()
}, 300)

// 节流处理状态变更
const throttledStatusChange = throttle(async (row) => {
  await handleStatusChange(row)
}, 1000)

// 获取用户列表数据
const getUserList = async () => {
  if (loading.value) return
  loading.value = true
  try {
    const params = {
      ...queryParams,
      status: queryParams.status
    }
    const res = await getPageList(params)
    if (res.code === 200) {
      userList.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error({
        message: res.msg || '获取用户列表失败',
        duration: 3000,
        showClose: true
      })
    }
  } catch (error) {
    console.error('获取用户列表出错:', error)
    // 403错误已在请求拦截器中处理，这里不再显示错误消息
    if (!error.code || error.code !== 403) {
      ElMessage.error({
        message: '获取用户列表出错，请稍后重试',
        duration: 3000,
        showClose: true
      })
    }
  } finally {
    loading.value = false
  }
}

// 格式化IP位置信息
const formatIpLocation = (ipInfo) => {
  // 当ipInfo为null时，显示未知信息
  if (!ipInfo) return '未知 | 未知 | 未知'

  // 当是内网IP时，显示内网IP信息
  if (ipInfo.city === '内网IP') {
    return '内网IP | 内网IP | 内网IP'
  }

  // 对于正常情况，检查每个字段是否为'0'，如果是则显示"未知"
  const country = ipInfo.country === '0' ? '未知' : (ipInfo.country || '未知')
  const province = ipInfo.province === '0' ? '未知' : (ipInfo.province || '未知')
  const city = ipInfo.city === '0' ? '未知' : (ipInfo.city || '未知')

  return `${country} | ${province} | ${city}`
}

// 查询按钮
const handleQuery = () => {

  queryParams.pageNum = 1
  debouncedQuery()
}

// 重置按钮
const resetQuery = () => {
  queryParams.name = ''
  queryParams.status = undefined
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  debouncedQuery()
}

// 页码变化
const handleCurrentChange = (current) => {
  queryParams.pageNum = current
  debouncedQuery()
}

// 状态变更
const handleStatusChange = async (row) => {
  const statusText = row.status === 0 ? '正常' : '封禁'
  const loading = ElLoading.service({
    lock: true,
    text: '正在更新用户状态...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const updateData = {
    id: row.id,
    status: row.status
  }
  updateStatus(updateData).then(res=>{
    if (res.code === 200) {
      ElMessage.success({
        message: `已将用户「${row.name}」的状态修改为${statusText}`,
        duration: 2000
      })
      getUserList() // 刷新列表
    } else {
      row.status = row.status === 0 ? 1 : 0
    }
  }).catch(error => {
    // 发生错误时，回滚UI状态 - 403错误已在请求拦截器中处理
    row.status = row.status === 0 ? 1 : 0
  }).finally(() => {
    loading.close()
  })
}

// 查看用户详情
const handleView = async (row) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载用户详情...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const res = await getById(row.id)
    if (res.code === 200) {
      currentUser.value = res.data
      dialogVisible.value = true
    } else {
      ElMessage.error({
        message: res.msg || '获取用户详情失败',
        duration: 3000,
        showClose: true
      })
    }
  } catch (error) {
    // 403错误已在请求拦截器中处理，这里不再显示错误消息
    if (!error.code || error.code !== 403) {
      ElMessage.error({
        message: '获取用户详情出错，请稍后重试',
        duration: 3000,
        showClose: true
      })
    }
  } finally {
    loading.close()
  }
}

// 编辑用户
const handleEdit = async (row) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载用户信息...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const res = await getById(row.id)
    if (res.code === 200) {
      editForm.value = {
        id: res.data.id,
        name: res.data.name,
        status: res.data.status,
        avatar: res.data.avatar,
        roles: res.data.roles || []
      }
      avatarFile.value = null
      editDialogVisible.value = true
    } else {
      ElMessage.error({
        message: res.msg || '获取用户详情失败',
        duration: 3000,
        showClose: true
      })
    }
  } catch (error) {
    // 403错误已在请求拦截器中处理，这里不再显示错误消息
    if (!error.code || error.code !== 403) {
      ElMessage.error({
        message: '获取用户详情出错，请稍后重试',
        duration: 3000,
        showClose: true
      })
    }
  } finally {
    loading.close()
  }
}

// 处理头像上传
const handleAvatarChange = async (file) => {
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return
  }
  
  // 验证文件大小（限制为2MB）
  const isLt2M = file.raw.size / 1024 / 1024 < 10
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过10MB！')
    return
  }

  avatarFile.value = file.raw

  // 显示加载中状态
  const loading = ElLoading.service({
    lock: true,
    text: '正在上传头像...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    // 立即上传头像到服务器
    const uploadRes = await uploadFile(file.raw, 1)
    if (uploadRes.code === 200) {
      // 上传成功，使用服务器返回的URL
      editForm.value.avatar = uploadRes.data
      ElMessage.success('头像上传成功')
    } else {
      // 上传失败，显示错误信息
      ElMessage.error(uploadRes.msg || '头像上传失败')
      // 预览本地图片作为备用
      const reader = new FileReader()
      reader.onload = (e) => {
        editForm.value.avatar = e.target.result
      }
    }
  } catch (error) {
    // 403错误已在请求拦截器中处理，这里不再显示错误消息
    if (!error.code || error.code !== 403) {
      ElMessage.error('头像上传出错，请稍后重试')
    }
    
  } finally {
    loading.close()
  }
}

// 提交编辑
const submitEdit = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (!valid) return

    submitLoading.value = true
    try {
      // 头像已在选择时上传，此处直接提交表单
      // 提交更新
      const updateData = {
        id: editForm.value.id,
        name: editForm.value.name,
        status: editForm.value.status,
        avatar: editForm.value.avatar,
        roles: editForm.value.roles || []
      }

      const res = await save(updateData)
      if (res.code === 200) {
        ElMessage.success('用户信息更新成功')
        editDialogVisible.value = false
        getUserList() // 刷新列表
      }
    } catch (error) {
      // 403错误已在请求拦截器中处理，这里不再显示错误消息
      if (!error.code || error.code !== 403) {
        ElMessage.error('更新用户信息出错')
      }
    } finally {
      submitLoading.value = false
    }
  })
}

// 处理清除
const handleClear = () => {
  queryParams.status = undefined
}

// 组件卸载时取消防抖和节流
onUnmounted(() => {
  debouncedQuery.cancel()
  throttledStatusChange.cancel()
})

// 获取角色列表数据
const getRoleList = async () => {
  try {
    const res = await getRolePageList({
      current: 1,
      size: 100
    })
    if (res.code === 200) {
      roleList.value = res.data.records
    } else {
      ElMessage.error(res.msg || '获取角色列表失败')
    }
  } catch (error) {
    // 403错误已在请求拦截器中处理，这里不再显示错误消息
    if (!error.code || error.code !== 403) {
      ElMessage.error('获取角色列表失败')
    }
  }
}

// 页面加载时获取数据
onMounted(() => {
  getUserList()
  getRoleList()
})
</script>

<style scoped>
.users-container {
  min-height: calc(100vh - 120px);
  background-color: #f5f7fa;
}

.main-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.card-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin: 0;
  line-height: 1.5;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.search-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.search-label {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.search-input,
.search-select {
  width: 220px;
}

.search-buttons {
  display: flex;
  gap: 10px;
  margin-top: 24px;
}

.table-section {
  padding: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-name {
  font-weight: 500;
  color: #303133;
}

.ip-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  color: #606266;
}

.ip-info .el-icon {
  font-size: 16px;
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.avatar-preview {
  border: 1px solid #ebeef5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  width: 100%;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .users-container {
    padding: 10px;
  }

  .search-container {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-item {
    width: 100%;
  }

  .search-input,
  .search-select {
    width: 100%;
  }

  .search-buttons {
    width: 100%;
    margin-top: 15px;
  }
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
}

.role-tag {
  margin: 2px;
}

.user-avatar {
  border: 1px solid #ebeef5;
  transition: transform 0.3s;
}

.user-avatar:hover {
  transform: scale(1.1);
}

.action-button {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
}

.action-button .el-icon {
  font-size: 16px;
}
</style>